// import _ from 'lodash';
import { segmentsIntr } from 'utils/util';
import MapCtrl, { ROW, COL, SIZE, RELIEF as relief } from './map';
import { scene } from 'utils/ScenseManager';

const { layer, items, meta } = relief;
const COLORS = ['#FF6666', '#993333', '#99CC66', '#3468d4', '#336699'];

// @scene('/panel')
export default class Panel extends Laya.Sprite {

  constructor() {
    super();
    this.size(SIZE * COL, SIZE * ROW);
    this.pos((Laya.stage.width - this.width) / 2, (Laya.stage.height - this.height) / 2);
    this.indicator = new Laya.Sprite();
    this.indicator.alpha = 0.5;
    this.addChild(this.indicator);

    this.init();
    this.initIndicator();
    setTimeout(() => {
      this.startUp();
    });
  }

  beforeEnter() {
    return new Promise(resolve => {
      Laya.loader.load([
        { url: 'res/atlas/comp.atlas', type: 'atlas' }
      ], Laya.Handler.create(null, resolve));
    });
  }

  init() {
    for (let j = 0; j <= ROW; j++) {
      this.graphics.drawLine(0, j * SIZE, SIZE * COL, j * SIZE, "#e1d84d", 1);
    }
    for (let i = 0; i <= COL; i++) {
      this.graphics.drawLine(i * SIZE, 0, i * SIZE, SIZE * ROW, "#e1d84d", 1);
    }

    layer.forEach((list, j) => {
      list.forEach((item, i) => {
        if (item != '0') {
          let str = item.split(':');
          this.graphics.drawRect(i * SIZE, j * SIZE, SIZE, SIZE, COLORS[str[0] | 0]);
        }
      });
    });
  }

  initIndicator() {
    let from = { x: 4 * 52 + 7, y: 4 * 52 + 8 };
    let rotation = 330;
    let angle = rotation * Math.PI / 180;
    let range = 800;

    this.indicator.graphics.drawCircle(from.x, from.y, 8, '#FF0033');
    this.points = [from.x, from.y];
    this.collideIndict(from, angle, range);
    this.indicator.graphics.drawLines(0, 0, this.points, '#ffffff', 14);
  }


  collideIndict(from, angle, range) {
    // console.log(from, angle, range);
    let { x: fromX, y: fromY } = from;
    let collided = false,
      px, py;
    const T = 10;
    for (let d = T; d <= range; d += T) {
      let vx = Math.cos(angle);
      let vy = Math.sin(angle);
      px = Math.round(fromX + vx * d);
      py = Math.round(fromY + vy * d);

      let grid = MapCtrl.getGridByPos(px, py);
      if (grid && grid.info != '0') {
        let { start, end, info } = grid;
        this.indicator.graphics.drawCircle(px, py, 8, '#FFCCCC');
        this.indicator.graphics.drawRect(start.x, start.y, SIZE, SIZE, '#FFCCCC');
        this.points.push(px, py);

        let sides = [
          [start.x, start.y, start.x, end.y],
          [start.x, end.y, end.x, end.y],
          [end.x, end.y, end.x, start.y],
          [end.x, start.y, start.x, start.y]
        ];

        for (let i = 0; i < 4; i++) {
          let v = sides[i];
          let p = segmentsIntr(from, { x: px, y: py }, { x: v[0], y: v[1] }, { x: v[2], y: v[3] });
          if (p) {
            if (i == 0 || i == 2) vx *= -1;
            else vy *= -1;
            px = Math.round(p.x), py = Math.round(p.y);
            from = { x: px, y: py };
            angle = Math.atan2(vy, vx);
            range -= d;
            collided = true;
            break;
          }
        }
        break;
      }
    }

    if (collided) {
      this.collideIndict(from, angle, range);
    } else {
      this.points.push(px, py);
    }

  }

  startUp() {
    Box2D().then(Box2D => {
      this.createWorld(Box2D);
      Laya.timer.frameLoop(1, this, this.step, []);
    });
  }

  createWorld(Box2D) {
    this.world = new Box2D.b2World(new Box2D.b2Vec2(0.0, 10.0));
    // let debugDraw = new Box2D.JSDraw();
    // world.SetDebugDraw(debugDraw);
    this.createBodies(Box2D);
  }

  createBodies(Box2D) {
    let bodies = this.bodies = [];
    let actors = this.actors = [];
    let world = this.world;

    const bd_ground = new Box2D.b2BodyDef();
    bd_ground.set_type(Box2D.b2_staticBody); //定义刚体对象为 静态对象. 即不收外力作用的对象，如地面，墙壁.

    // create ground
    let ground = world.CreateBody(bd_ground);
    let shape0 = new Box2D.b2EdgeShape();
    shape0.Set(new Box2D.b2Vec2(0.0, 6.60), new Box2D.b2Vec2(13.34, 6.60));
    ground.CreateFixture(shape0, 0.0);

    let left_wall = world.CreateBody(bd_ground);
    let shape1 = new Box2D.b2EdgeShape();
    shape1.Set(new Box2D.b2Vec2(0.0, 0.0), new Box2D.b2Vec2(0.0, 7.5));
    left_wall.CreateFixture(shape1, 0.0);

    let right_wall = world.CreateBody(bd_ground);
    let shape2 = new Box2D.b2EdgeShape();
    shape2.Set(new Box2D.b2Vec2(13.34, 0.0), new Box2D.b2Vec2(13.34, 7.5));
    right_wall.CreateFixture(shape2, 0.0);

    const size = 0.6;

    const shape = new Box2D.b2PolygonShape();
    shape.SetAsBox(size, size);

    const circleShape = new Box2D.b2CircleShape();
    circleShape.set_m_radius(size);

    let fixtureDef = new Box2D.b2FixtureDef();
    fixtureDef.set_density(10.0); // desity 密度，如果密度为0或者null，该物体则为一个静止对象
    fixtureDef.set_friction(0.1); //摩擦力（0~1）
    fixtureDef.set_restitution(0.7); // 弹性（0~1）
    fixtureDef.set_shape(circleShape);

    for (var i = 0; i < 10; i++) {
      var bd = new Box2D.b2BodyDef();
      bd.set_type(Box2D.b2_dynamicBody);
      bd.set_position(new Box2D.b2Vec2(Math.random() * 5 + 2, 0.0));
      var body = world.CreateBody(bd);
      body.CreateFixture(fixtureDef);
      bodies.push(body);

      let sp = new Laya.Sprite();
      sp.graphics.drawCircle(0, 0, size * 100, '#6699CC');
      this.addChild(sp);
      actors.push(sp);
    }

  }

  step() {
    let { world } = this;
    world.Step(1 / 60, 1, 1);
    world.ClearForces();
    this.draw();
  }

  draw() {
    let { bodies, actors } = this;
    for (var i = 0; i < bodies.length; i++) {
      var body = bodies[i];
      var actor = actors[i];
      var p = body.GetPosition();
      actor.x = p.get_x() * 100;
      actor.y = p.get_y() * 100;
      actor.rotation = body.GetAngle() * 180 / Math.PI;
    }
  }

}